package com.nmgs.util.zip;

import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

public class RarUtil {
    private static final Logger logger = LoggerFactory.getLogger(RarUtil.class);

    /**
     * 解压rar格式的压缩包
     *
     * @param sourcePath 待解压文件
     * @param targetPath 解压路径
     */
    public static void unCompressRar(String sourcePath, String targetPath) {
        //File sourceFile = FileUtil.validateSourcePath(sourcePath);
        unCompressRar(new File(sourcePath), targetPath);
    }

    public static void unCompressRar(File sourceFile, String targetPath) {
        //校验解压地址是否存在
        // FileUtil.validateTargetPath(targetPath);
        logger.info("start to unpack rar file, file name:{}", sourceFile.getName());
        long start = System.currentTimeMillis();
        System.out.println("absolute path is ============= " + sourceFile.getAbsolutePath());
        try (Archive archive = new Archive(new FileInputStream(sourceFile))) {
            FileHeader fileHeader = archive.nextFileHeader();
            while (fileHeader != null) {
                //如果是文件夹
                if (fileHeader.isDirectory()) {
                    fileHeader = archive.nextFileHeader();
                    continue;
                }
                //防止文件名中文乱码问题的处理
                File out = new File(String.format("%s%s%s", targetPath, File.separator, fileHeader.getFileNameW()));
                if (!out.exists()) {
                    if (!out.getParentFile().exists()) {
                        out.getParentFile().mkdirs(); //相对路径可能多级，可能需要创建父目录.
                    }
                    out.createNewFile();
                }
                try (FileOutputStream os = new FileOutputStream(out)) {
                    archive.extractFile(fileHeader, os);
                } catch (RarException e) {
                    logger.error("unpack rar throw exception, filename:{}, e:{}", sourceFile.getName(), e);
                }
                fileHeader = archive.nextFileHeader();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (RarException e) {
            logger.error("unpack rar throw exception, file name:{}, e:{}", sourceFile.getName(), e);
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("finish unpack rar file, file name:{}, cost:{} ms", sourceFile.getName(), System.currentTimeMillis() - start);
    }
}
